import { Component, OnInit } from '@angular/core';
import { mergeMap, map } from 'rxjs/operators';
import { HttpClient } from '@angular/common/http';

@Component({
  selector: 'app-mergemap',
  templateUrl: './mergemap.component.html',
  styleUrls: ['./mergemap.component.less']
})
export class MergemapComponent implements OnInit {

  constructor(private http: HttpClient) { }

  ngOnInit() {
    // 串联请求, 前面请求会影响后面的请求，前面请求未请求到，后面请求中断；
    const httpThis = this;
    httpThis.http.get('/api/token').
      pipe(
        map(token => {
          return token;
        }),
        mergeMap((tokenRes: any) => { // tokenRes接收的是token数据
          return httpThis.http.get(`/api/user?token=${tokenRes}`)
            .pipe((user) => {
              return user;
            });
        }),
        mergeMap((userRes: any) => { // userRes接收的是user数据
          return httpThis.http.get(`api/data?user=${userRes}`)
            .pipe((data) => {
              return data;
            });
        }))
      .subscribe((resp) => { // resp接收的是data数据
        console.log('最终结果resp是最后一个mergeMap的data');
      });
  }
}
